from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QTreeWidget, 
                             QTreeWidgetItem, QLabel, QComboBox,
                             QHBoxLayout, QGroupBox, QLineEdit, QPushButton, QListWidget, QListWidgetItem)
from PyQt6.QtCore import pyqtSignal, Qt
from question_bank import QuestionBank
from datetime import datetime

class LeftPanel(QWidget):
    knowledge_selected = pyqtSignal(str)  # 知识点选择信号
    filter_changed = pyqtSignal(dict)  # 筛选条件变化信号
    
    def __init__(self, question_bank):
        super().__init__()
        self.question_bank = question_bank
        self.current_filters = {
            'difficulty': "全部",
            'review_status': "全部",
            'favorite_status': "全部",
            'knowledge_tags': [],  # 改为列表存储多个知识点标签
            'subject': "全部"
        }
        self.init_ui()
        self.setup_styles()
    
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 学科选择组
        subject_group = QGroupBox("学科")
        subject_layout = QVBoxLayout()
        self.subject_combo = QComboBox()
        self.subject_combo.addItems(["全部", "问的问题", "数学", "物理", "化学", "生物"])
        self.subject_combo.currentTextChanged.connect(self.on_subject_changed)
        subject_layout.addWidget(self.subject_combo)
        subject_group.setLayout(subject_layout)
        layout.addWidget(subject_group)
        
        # 难度筛选组
        difficulty_group = QGroupBox("难度")
        difficulty_layout = QVBoxLayout()
        self.difficulty_combo = QComboBox()
        self.difficulty_combo.addItems(["全部", "简单", "中等", "困难"])
        self.difficulty_combo.currentTextChanged.connect(self.on_filter_changed)
        difficulty_layout.addWidget(self.difficulty_combo)
        difficulty_group.setLayout(difficulty_layout)
        layout.addWidget(difficulty_group)
        
        # 复习状态筛选组
        review_group = QGroupBox("复习状态")
        review_layout = QVBoxLayout()
        self.review_combo = QComboBox()
        self.review_combo.addItems(["全部", "未复习", "已复习", "最近复习"])
        self.review_combo.currentTextChanged.connect(self.on_filter_changed)
        review_layout.addWidget(self.review_combo)
        review_group.setLayout(review_layout)
        layout.addWidget(review_group)
        
        # 收藏状态筛选组
        favorite_group = QGroupBox("收藏状态")
        favorite_layout = QVBoxLayout()
        self.favorite_combo = QComboBox()
        self.favorite_combo.addItems(["全部", "已收藏", "未收藏"])
        self.favorite_combo.currentTextChanged.connect(self.on_filter_changed)
        favorite_layout.addWidget(self.favorite_combo)
        favorite_group.setLayout(favorite_layout)
        layout.addWidget(favorite_group)
        
        # 步骤筛选组
        step_group = QGroupBox("步骤筛选")
        step_layout = QVBoxLayout()
        self.step_input = QLineEdit()
        self.step_input.setPlaceholderText("输入步骤关键词...")
        self.step_input.textChanged.connect(self.on_filter_changed)
        step_layout.addWidget(self.step_input)
        step_group.setLayout(step_layout)
        layout.addWidget(step_group)
        
        # 知识点列表
        knowledge_group = QGroupBox("知识点")
        knowledge_layout = QVBoxLayout()
        self.tag_list = QListWidget()
        self.tag_list.setStyleSheet("""
            QListWidget {
                background-color: #1E1E1E;
                border: none;
                color: #FFFFFF;
                font-size: 13px;
            }
            QListWidget::item {
                padding: 6px 8px;
                border-bottom: 1px solid #2D2D2D;
            }
            QListWidget::item:hover {
                background-color: #2D2D2D;
            }
            QListWidget::item:selected {
                background-color: #2196F3;
            }
        """)
        self.tag_list.itemClicked.connect(self.on_tag_clicked)
        knowledge_layout.addWidget(self.tag_list)
        knowledge_group.setLayout(knowledge_layout)
        layout.addWidget(knowledge_group)
        
        # 重置按钮
        reset_button = QPushButton("重置筛选")
        reset_button.clicked.connect(self.reset_filters)
        layout.addWidget(reset_button)
        
        # 设置布局比例
        layout.setStretch(0, 1)  # 学科选择
        layout.setStretch(1, 1)  # 难度筛选
        layout.setStretch(2, 1)  # 复习状态
        layout.setStretch(3, 1)  # 收藏状态
        layout.setStretch(4, 1)  # 步骤筛选
        layout.setStretch(5, 3)  # 知识点列表
        layout.setStretch(6, 1)  # 重置按钮
        
        # 加载知识点
        self.update_tag_list()
    
    def update_tag_list(self):
        """更新标签列表"""
        try:
            self.tag_list.clear()
            
            # 获取当前选择的学科
            current_subject = self.subject_combo.currentText()
            
            # 获取所有标签及其正确率
            tag_stats = {}
            for question in self.question_bank.questions:
                # 如果选择了特定学科，只处理该学科的题目
                if current_subject != "全部":
                    # 从题目内容或标签中判断学科
                    question_subject = self._get_question_subject(question)
                    if question_subject != current_subject:
                        continue
                
                if isinstance(question.get('tags', {}).get('knowledge_tags'), list):
                    for tag in question['tags']['knowledge_tags']:
                        if tag not in tag_stats:
                            tag_stats[tag] = {
                                'total': 0,
                                'correct': 0
                            }
                        tag_stats[tag]['total'] += 1
                        if question.get('correct_count', 0) > 0:
                            tag_stats[tag]['correct'] += 1
            
            # 计算每个标签的正确率并排序
            sorted_tags = []
            for tag, stats in tag_stats.items():
                accuracy = stats['correct'] / stats['total'] if stats['total'] > 0 else 0
                sorted_tags.append((tag, accuracy, stats['total']))
            
            # 按正确率降序排序
            sorted_tags.sort(key=lambda x: (-x[1], -x[2]))
            
            # 添加到列表
            for tag, accuracy, total in sorted_tags:
                item = QListWidgetItem(f"{tag} ({accuracy:.0%}, {total}题)")
                item.setData(Qt.ItemDataRole.UserRole, tag)  # 存储原始标签
                self.tag_list.addItem(item)
            
        except Exception as e:
            print(f"更新标签列表失败: {e}")
    
    def _get_question_subject(self, question):
        """判断题目所属学科"""
        try:
            # 获取题目内容
            if isinstance(question, dict):
                content = question.get('question', '')
            else:
                content = question.question
            
            # 转换为小写以进行匹配
            content = str(content).lower()
            
            # 定义学科关键词
            subject_keywords = {
                "数学": ["数学", "代数", "几何", "函数", "方程", "不等式", "概率", "统计", "数列", "三角函数", "导数", "积分"],
                "物理": ["物理", "力学", "电学", "光学", "热学", "声学", "运动", "能量", "动量", "电场", "磁场", "电路"],
                "化学": ["化学", "元素", "反应", "分子", "原子", "离子", "溶液", "酸碱", "氧化", "还原", "化学键", "化学式"],
                "生物": ["生物", "细胞", "遗传", "进化", "生态", "生理", "解剖", "微生物", "基因", "蛋白质", "酶", "代谢"]
            }
            
            # 检查每个学科的关键词
            for subject, keywords in subject_keywords.items():
                for keyword in keywords:
                    if keyword in content:
                        return subject
            
            # 如果没有找到明确的学科标识，返回默认学科
            return "问的问题"
            
        except Exception as e:
            print(f"判断题目学科时出错: {e}")
            return "问的问题"
    
    def on_tag_clicked(self, item):
        """处理标签点击事件"""
        try:
            tag = item.data(Qt.ItemDataRole.UserRole)
            if tag:
                # 更新筛选条件
                self.current_filters['knowledge_tags'] = [tag]
                # 发送筛选信号
                self.emit_filters()
        except Exception as e:
            print(f"处理标签点击事件失败: {e}")
    
    def on_subject_changed(self, subject):
        """处理学科选择变化"""
        print(f"Subject changing to: {subject}")
        # 更新筛选条件
        self.current_filters['subject'] = subject
        self.current_filters['knowledge_tags'] = []  # 清空已选知识点
        # 重新加载知识点树
        self.update_tag_list()
        # 发送筛选信号
        self.emit_filters()
        
        # 打印调试信息
        print(f"Subject changed to: {subject}")
        print(f"Current filters: {self.current_filters}")
        print(f"Filtered questions count: {len(self.question_bank.filter_questions(self.current_filters))}")
    
    def on_filter_changed(self):
        """处理筛选条件变化"""
        self.current_filters.update({
            'difficulty': self.difficulty_combo.currentText(),
            'review_status': self.review_combo.currentText(),
            'favorite_status': self.favorite_combo.currentText(),
            'step_keyword': self.step_input.text()
        })
        self.emit_filters()
    
    def emit_filters(self):
        """发送筛选条件"""
        self.filter_changed.emit(self.current_filters)
    
    def reset_filters(self):
        """重置所有筛选条件"""
        self.difficulty_combo.setCurrentText("全部")
        self.review_combo.setCurrentText("全部")
        self.favorite_combo.setCurrentText("全部")
        self.step_input.clear()
        self.subject_combo.setCurrentText("全部")
        self.tag_list.clear()
        self.current_filters = {
            'difficulty': "全部",
            'review_status': "全部",
            'favorite_status': "全部",
            'knowledge_tags': [],
            'subject': "全部"
        }
        self.emit_filters()
    
    def setup_styles(self):
        """设置样式"""
        self.setStyleSheet("""
            QWidget {
                background-color: #1E1E1E;
                color: #FFFFFF;
            }
            
            QGroupBox {
                border: 1px solid #404040;
                border-radius: 4px;
                margin-top: 1em;
                padding-top: 0.5em;
            }
            
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 3px;
                color: #2196F3;
            }
            
            QComboBox {
                background-color: #2D2D2D;
                border: 1px solid #404040;
                border-radius: 4px;
                padding: 5px;
                color: #FFFFFF;
                min-height: 25px;
            }
            
            QComboBox:hover {
                border-color: #2196F3;
            }
            
            QComboBox::drop-down {
                border: none;
                width: 20px;
            }
            
            QComboBox::down-arrow {
                image: url(down_arrow.png);
                width: 12px;
                height: 12px;
            }
            
            QLineEdit {
                background-color: #2D2D2D;
                border: 1px solid #404040;
                border-radius: 4px;
                padding: 5px;
                color: #FFFFFF;
                min-height: 25px;
            }
            
            QLineEdit:hover {
                border-color: #2196F3;
            }
            
            QTreeWidget {
                background-color: #2D2D2D;
                border: 1px solid #404040;
                border-radius: 4px;
            }
            
            QTreeWidget::item {
                padding: 5px;
                min-height: 25px;
            }
            
            QTreeWidget::item:selected {
                background-color: #3D3D3D;
            }
            
            QTreeWidget::item:hover {
                background-color: #3D3D3D;
            }
            
            QPushButton {
                background-color: #2196F3;
                color: #FFFFFF;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                min-height: 25px;
            }
            
            QPushButton:hover {
                background-color: #1976D2;
            }
            
            QPushButton:pressed {
                background-color: #1565C0;
            }
        """) 